﻿using System;
using System.Web;
using Newtonsoft.Json;
using Web.Base.Security;
using System.Web.WebPages;
using System.Web.SessionState;
using Ayatta.Common.Extensions;
using Ayatta.Contract.Component;

namespace Web.Base.Handlers
{
    public abstract class BaseHandler : IHttpHandler, IRequiresSessionState
    {

        private string action = string.Empty;
        public string Action { get { return action.ToLower(); } }
        protected Identity Identity { get; private set; }

        protected Func<HttpRequest, SkResult<object>> Func { get; set; }

        protected abstract void Process(HttpRequest request);

        public void ProcessRequest(HttpContext context)
        {
            Identity = context.User.Identity.Identity();
            action = context.Request.QueryString.AsDynamic().Action;
            if (!string.IsNullOrEmpty(action))
            {
                try
                {
                    Process(context.Request);
                    if (Func != null)
                    {
                        if (!string.IsNullOrEmpty(context.Request.QueryString["jsvar"]))
                        {
                            var r = Func(context.Request);
                            r.Extra = context.Request.QueryString["jsvar"];
                            ReturnJsResult(context.Response, r);
                        }
                        else
                        {
                            ReturnResult(context.Response, Func(context.Request));
                        }
                    }
                }
                catch (Exception e)
                {
                    var result = new SkResult<string>(e.Message);
                    ReturnResult(context.Response, result);
                }
            }
            else
            {
                var result = new SkResult<string>("缺少action参数！");
                ReturnResult(context.Response, result);
            }
        }

        private static void ReturnResult<T>(HttpResponse response, SkResult<T> result)
        {
            response.ContentType = "application/json";
            var data = JsonConvert.SerializeObject(result);
            response.Write(data);
            response.Flush();
            response.End();
        }

        private static void ReturnJsResult<T>(HttpResponse response, SkResult<T> result)
        {
            response.ContentType = "text/javascript";
            var data = JsonConvert.SerializeObject(result.Data);
            var s = string.Format("var {0}={1};", result.Extra, data);
            response.Write(s);
            response.Flush();
            response.End();
        }

        protected T GetCookie<T>(string key)
        {
            var cookie = HttpContext.Current.Request.Cookies[key];
            return cookie != null ? cookie.Value.As<T>() : default(T);
        }

        protected void WriteCookie(HttpCookie cookie)
        {
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        protected bool ValidateCaptcha(string captchaKey, string captchaTxt)
        {
            var session = HttpContext.Current.Session;
            if (session != null)
            {
                return session[captchaKey].ToString() == captchaTxt.ToLower();
            }
            return false;
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}